//
//  GYMineProductInfoEditVC.m
//  GYDemo
//
//  Created by mac on 2018/3/30.
//  Copyright © 2018年 mac. All rights reserved.
//

//
//                .-~~~~~~~~~-._       _.-~~~~~~~~~-.
//            __.'              ~.   .~              `.__
//          .'//                  \./                  \\`.
//        .'//                     |                     \\`.
//      .'// .-~"""""""~~~~-._     |     _,-~~~~"""""""~-. \\`.
//    .'//.-"                 `-.  |  .-'                 "-.\\`.
//  .'//______.============-..   \ | /   ..-============.______\\`.
//.'______________________________\|/______________________________`.
//
//

#import "GYMineProductInfoEditVC.h"
#import "Head.h"
#import "GYCategoryPickerView.h"

@interface GYMineProductInfoEditVC ()<ACEExpandableTableViewDelegate,GYMineProductImageViewDelegate>
{
    NSArray *actions;
}
@property (nonatomic,strong) UIButton *saveBtn;
@end

@implementation GYMineProductInfoEditVC
#pragma mark - getter and setter
-(GYMineProductInfoEditViewModel *)productInfoEditViewModel
{
    if (!_productInfoEditViewModel) {
        _productInfoEditViewModel = [GYMineProductInfoEditViewModel new];
    }
    return _productInfoEditViewModel;
}
-(UIButton *)saveBtn
{
    if (!_saveBtn) {
        _saveBtn = [UIButton new];
        _saveBtn.x = 0;
        _saveBtn.width = self.view.width;
        _saveBtn.height = WFCGFloatY(50);
        _saveBtn.y = WF_SCREEN_HEIGHT - self.topShelterHeight - self.bottomShelterHeight - _saveBtn.height;
        _saveBtn.titleLabel.font = SYSTEMFONT(15);
        [_saveBtn setTitle:@"保存" forState:UIControlStateNormal];
        [_saveBtn setBackgroundColor:Main_Color_Red forState:UIControlStateNormal];
        [_saveBtn setTitleColor:Main_Color_White forState:UIControlStateNormal];
        [_saveBtn addTarget:self action:@selector(saveBtnTap:) forControlEvents:UIControlEventTouchUpInside];
        _saveBtn.layer.borderColor = Main_Color_White.CGColor;
        _saveBtn.layer.borderWidth = 4;
    }
    return _saveBtn;
}
#pragma mark - event
-(void)saveBtnTap:(id)sender
{
    [self.productInfoEditViewModel requestSave];
}
#pragma mark - method
-(void)initilization
{
    self.navigationItem.title = @"我的产品信息";
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.edgesForExtendedLayout = UIRectEdgeNone;
    
    self.navigationController.navigationBar.shadowImage = [[UIImage new]rt_darkenWithLevel:0.3f];
    [self setNavgationTheme:1];
    [self.view addSubview:self.baseTable];
    [self.baseTable setSeparatorStyle:UITableViewCellSeparatorStyleSingleLine];
    [self.baseTable setSeparatorColor: Main_Color_BG];
    [self.baseTable setBackgroundColor:Main_Color_BG];
    [self.baseTable setTintColor:Main_Color_BG];
    self.baseTable.height = self.saveBtn.y;
    if (@available(iOS 11.0, *)) {
        //        self.baseTable.contentInset = UIEdgeInsetsMake(-64, 0, 0, 0);
    }
    self.baseTable.mj_header.backgroundColor = Main_Color_Red;
    self.baseTable.scrollIndicatorInsets = self.baseTable.contentInset;
    UIView *foot = [UIView new];
    foot.height = self.saveBtn.height;
    [self.baseTable setTableFooterView:foot];
    
    [self.view addSubview:self.saveBtn];
    [self viewModelBand];
    
    //
    actions = @[@"chooseCatogery:",@"chooseArea:",@"inputPrice:",@"chooseImage:",@"otherProperty:"];
}
-(void)viewModelBand
{
    @WeakSelf;
    GCBaseObservationModel *observation = [GCBaseObservationModel new];
    observation.observation = self.productInfoEditViewModel;
    observation.keyPath = @"updateSign";
    observation.handler = ^(NSString *keyPath) {
        [selfp.detailVC reloadData];
        [selfp.listVC refreshData];
        [selfp.navigationController popViewControllerAnimated:YES];
    };
    [self registObservation:observation];
    
    GCBaseObservationModel *observation2 = [GCBaseObservationModel new];
    observation2.observation = self.productInfoEditViewModel;
    observation2.keyPath = @"detailSpecialItems";
    observation2.handler = ^(NSString *keyPath) {
        [selfp reloadView];
    };
    [self registObservation:observation2];
}
-(void)reloadView
{
    [self.baseTable reloadData];
}

///选择类别
-(void)chooseCatogery:(GYMineProductInfoEditDetailCellModel *)model
{
    @WeakSelf;
    [GYCategoryPickerView showAddressPickerWithShowType:BRAddressPickerModeArea dataSource:nil defaultSelected:nil isAutoSelect:NO themeColor:Main_Color_Black resultBlock:^(FirstCategoryModel *province, SecondCategoryModel *city, ThirdCategoryModel *area) {
        NSString *idd = [NSString stringWithFormat:@"%@",area.code];
        NSDictionary *datasource = area.dataSource;
        NSString *unit = datasource[@"unit"];
        
        NSMutableDictionary *para = [NSMutableDictionary new];
        [para setObject:idd forKey:@"id"];
        [selfp.productInfoEditViewModel requestType:para];
        
        [selfp.productInfoEditViewModel.updateModel setProtypeid:idd];
        selfp.productInfoEditViewModel.updateModel.unit = unit;
        model.value = area.name;
    } cancelBlock:^{
        
    }];
}
///选择区域
-(void)chooseArea:(GYMineProductInfoEditDetailCellModel *)model
{
    @WeakSelf;
    
    [BRAddressPickerView showAddressPickerWithShowType:BRAddressPickerModeArea dataSource:[WFFunctions getLocalAddressList] defaultSelected:nil isAutoSelect:nil themeColor:Main_Color_Black resultBlock:^(BRProvinceModel *province, BRCityModel *city, BRAreaModel *area) {
        
        NSString *areas = [NSString stringWithFormat:@"%@%@%@",province.name,city.name,area.name];
        model.value = areas;
        selfp.productInfoEditViewModel.updateModel.province = [WFFunctions replaceZerofromStr:province.code];
        selfp.productInfoEditViewModel.updateModel.city = [WFFunctions replaceZerofromStr:city.code];
        selfp.productInfoEditViewModel.updateModel.area = [WFFunctions replaceZerofromStr:area.code];
        [selfp.baseTable reloadData];
    } cancelBlock:^{
        
    }];
    
}
///输入价格区间
-(void)inputPrice:(GYMineProductInfoEditDetailCellModel *)model
{
    NSString *title = @"价格";
    NSString *hold1 = @"请输入价格";
    TYAlertView *alertView = [TYAlertView alertViewWithTitle:title message:nil];
    [alertView addAction:[TYAlertAction actionWithTitle:@"取消" style:TYAlertActionStyleCancel handler:^(TYAlertAction *action) {
        NSLog(@"%@",action.title);
    }]];
    @WeakSelf;
    [alertView addAction:[TYAlertAction actionWithTitle:@"确定" style:TYAlertActionStyleDestructive handler:^(TYAlertAction *action) {
        UITextField *mintf = alertView.textFieldArray[0];
        if (mintf.text.length > 0) {
            NSString *min = mintf.text;
            selfp.productInfoEditViewModel.updateModel.price = min;
            model.value = min;
            [selfp.baseTable reloadData];
        }else{
            [FTToastIndicator showToastMessage:@"请填写完整"];
        }
    }]];
    
    [alertView addTextFieldWithConfigurationHandler:^(UITextField *textField) {
        textField.placeholder = hold1;
        textField.keyboardType = UIKeyboardTypeNumberPad;
    }];
    alertView.clickedAutoHide = YES;
    TYAlertController *alertController = [TYAlertController alertControllerWithAlertView:alertView preferredStyle:TYAlertControllerStyleAlert];
    
    //alertController.alertViewOriginY = 60;
    [self presentViewController:alertController animated:YES completion:nil];
}
///选择图片
-(void)chooseImage:(GYMineProductInfoEditDetailCellModel *)model
{
    [self chooseImageWithHandler:^(UIImage *img, NSError *err) {
        if (img) {
            @WeakSelf;
            NSData *imageData = UIImageJPEGRepresentation(img, 0.6);
            NSDate *sendDate = [NSDate date];
            NSString *date = [NSString stringWithFormat:@"%ld", (long)[sendDate timeIntervalSince1970]];
            [FCFileManager createFileAtPath:date withContent:imageData];
            NSURL *imgUrl = [NSURL URLWithString:[FCFileManager pathForDocumentsDirectoryWithPath:date]];
            [FTIndicator showProgressWithMessage:@"请稍后"];
            [[GYAliyunOSS sharedInstance] uploadObjectSyncWithImageUrl:imgUrl dir:kProduct completion:^(NSDictionary *error, NSString *imgPath) {
                if (error == nil) {
                    [FCFileManager removeItemAtPath:date];
                    NSArray *arr = self.productInfoEditViewModel.detailItems[0];
                    GYMineProductInfoEditDetailCellModel *cellmodel = arr[6];
                    NSLog(@"cellmodel.cellHeight : %f",cellmodel.cellHeight);
                    cellmodel.imgUrl = [NSString stringWithFormat:@"%@%@",imgPath,kProductImgThumbnailSuffix];
                    selfp.productInfoEditViewModel.updateModel.imgUrl = imgPath;
                    kDISPATCH_MAIN_THREAD(^(){
                        [FTIndicator dismissProgress];
                        [selfp.baseTable reloadData];
                        NSLog(@"上传文件的名称======:%@", imgPath);
                    });
                    
                } else {
                    dispatch_async(dispatch_get_main_queue(), ^{
                        [FTIndicator showErrorWithMessage:@"抱歉，上传图片失败"];
                    });
                }
            }];
        }
    }];
}
///
-(void)otherProperty:(GYMineProductInfoEditDetailCellModel *)model
{
    NSArray *data = model.other[@"data"];
    if ([data isKindOfClass:[NSArray class]]) {
        @WeakSelf;
        TYAlertView *alertView = [TYAlertView alertViewWithTitle:@"选择" message:nil];
        for (NSDictionary *dic in data) {
            NSString *provalue = dic[@"provalue"] ?: @"";
            [alertView addAction:[TYAlertAction actionWithTitle:provalue style:TYAlertActionStyleDefault handler:^(TYAlertAction *action) {
                model.value = provalue;
                [selfp.productInfoEditViewModel.updateModel.otherInfo setValue:provalue forKey:model.key];
                [selfp.baseTable reloadData];
            }]];
        }
        alertView.clickedAutoHide = YES;
        TYAlertController *alertController = [TYAlertController alertControllerWithAlertView:alertView preferredStyle:TYAlertControllerStyleActionSheet];
        //alertController.alertViewOriginY = 60;
        [self presentViewController:alertController animated:YES completion:nil];
    }
}
#pragma mark - life
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self initilization];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */
#pragma mark - delegate
#pragma mark - GYMineProductImageViewDelegate
-(void)chooseImages:(NSMutableArray *)images
{
    NSMutableArray *marr = [NSMutableArray new];
    for (NSString *picurl in images) {
        NSDictionary *dic = @{@"picurl":picurl};
        [marr addObject:dic];
    }
    NSData *data;
    NSString *imgUrl = @"";
    if (@available(iOS 11.0, *)) {
        data = [NSJSONSerialization dataWithJSONObject:marr options:NSJSONWritingPrettyPrinted | NSJSONWritingSortedKeys error:nil];
    } else {
        data = [NSJSONSerialization dataWithJSONObject:marr options:NSJSONWritingPrettyPrinted error:nil];
    }
    imgUrl = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
    self.productInfoEditViewModel.updateModel.imgUrl = imgUrl;
}
#pragma mark - table
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return self.productInfoEditViewModel.detailItems.count;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    NSArray *arr = self.productInfoEditViewModel.detailItems[section];
    return arr.count;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    NSArray *arr = self.productInfoEditViewModel.detailItems[indexPath.section];
    GYMineProductInfoEditDetailCellModel *cellmodel = arr[indexPath.row];
    CGFloat height = cellmodel.cellHeights.floatValue;
    return height;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *CellID = @"CellID";
    NSArray *arr = self.productInfoEditViewModel.detailItems[indexPath.section];
    GYMineProductInfoEditDetailCellModel *cellmodel = arr[indexPath.row];
    GYMineProductInfoEditDetailCell *cell = [tableView dequeueReusableCellWithIdentifier:CellID];
    if (!cell) {
        cell = [[GYMineProductInfoEditDetailCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:CellID];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.expandableTableView = tableView;
    }
    cell.specialType = cellmodel.specialType;
    cell.titleLB.text = cellmodel.title;
    cell.textView.text = cellmodel.value;
    CGFloat cellheight = [cell cellHeight];
    cellmodel.cellHeight = cellheight;
    cell.textView.editable = cellmodel.isEditable;
    cell.textView.userInteractionEnabled = cell.textView.editable;
    cell.textView.keyboardType = cellmodel.inputType;
    if ([cellmodel.imgUrl isEqualToString:@"(null)@!s1"])
    {
        cell.imageIV.image=[UIImage imageNamed:@"tjtp"];
    }else{
        [cell.imageIV sd_setImageWithURL:[NSURL URLWithString:cellmodel.imgUrl]];
    }
    cell.imagesV.imageS = cellmodel.imgs;
    cell.imagesV.delegate = self;
    return cell;
}
-(void)tableView:(UITableView* )tableView willDisplayCell:(UITableViewCell* )cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    [cell setSeparatorInset:UIEdgeInsetsMake(0, WFCGFloatX(13), 0, 0)];
    [cell setLayoutMargins:UIEdgeInsetsZero];
}
-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 5;
}
-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    UIView *view = [UIView new];
    view.backgroundColor = Main_Color_BG;
    return view;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSArray *arr = self.productInfoEditViewModel.detailItems[indexPath.section];
    GYMineProductInfoEditDetailCellModel *cellmodel = arr[indexPath.row];
    NSString *action = cellmodel.action;
    if (action && [actions containsObject:action]) {
        SEL selector = NSSelectorFromString(action);
        [self performSelector:selector withObject:cellmodel];
    }
}
#pragma mark - ace delegate
- (void)tableView:(UITableView *)tableView updatedText:(NSString *)text atIndexPath:(NSIndexPath *)indexPath {
    NSArray *arr = self.productInfoEditViewModel.detailItems[indexPath.section];
    GYMineProductInfoEditDetailCellModel *cellmodel = arr[indexPath.row];
    if (cellmodel.isEditable) {
        NSString *key = cellmodel.key;
        cellmodel.value = text;
        [self.productInfoEditViewModel.updateModel setValue:text forKey:key];
    }
}
-(void)tableView:(UITableView *)tableView updatedHeight:(CGFloat)height atIndexPath:(NSIndexPath *)indexPath
{
    NSArray *arr = self.productInfoEditViewModel.detailItems[indexPath.section];
    GYMineProductInfoEditDetailCellModel *cellmodel = arr[indexPath.row];
    if (cellmodel.isExpandable) {
        NSLog(@"updatedHeight %.2f",height);
        NSString *cellheights = [NSString stringWithFormat:@"%f",height];
        cellmodel.cellHeights = cellheights;
    }
}
@end


/*
 11111111111111111111111111111111111111001111111111111111111111111
 11111111111111111111111111111111111100011111111111111111111111111
 11111111111111111111111111111111100001111111111111111111111111111
 11111111111111111111111111111110000111111111111111111111111111111
 11111111111111111111111111111000000111111111111111111111111111111
 11111111111111111111111111100000011110001100000000000000011111111
 11111111111111111100000000000000000000000000000000011111111111111
 11111111111111110111000000000000000000000000000011111111111111111
 11111111111111111111111000000000000000000000000000000000111111111
 11111111111111111110000000000000000000000000000000111111111111111
 11111111111111111100011100000000000000000000000000000111111111111
 11111111111111100000110000000000011000000000000000000011111111111
 11111111111111000000000000000100111100000000000001100000111111111
 11111111110000000000000000001110111110000000000000111000011111111
 11111111000000000000000000011111111100000000000000011110001111111
 11111110000000011111111111111111111100000000000000001111100111111
 11111111000001111111111111111111110000000000000000001111111111111
 11111111110111111111111111111100000000000000000000000111111111111
 11111111111111110000000000000000000000000000000000000111111111111
 11111111111111111100000000000000000000000000001100000111111111111
 11111111111111000000000000000000000000000000111100000111111111111
 11111111111000000000000000000000000000000001111110000111111111111
 11111111100000000000000000000000000000001111111110000111111111111
 11111110000000000000000000000000000000111111111110000111111111111
 11111100000000000000000001110000001111111111111110001111111111111
 11111000000000000000011111111111111111111111111110011111111111111
 11110000000000000001111111111111111100111111111111111111111111111
 11100000000000000011111111111111111111100001111111111111111111111
 11100000000001000111111111111111111111111000001111111111111111111
 11000000000001100111111111111111111111111110000000111111111111111
 11000000000000111011111111111100011111000011100000001111111111111
 11000000000000011111111111111111000111110000000000000011111111111
 11000000000000000011111111111111000000000000000000000000111111111
 11001000000000000000001111111110000000000000000000000000001111111
 11100110000000000001111111110000000000000000111000000000000111111
 11110110000000000000000000000000000000000111111111110000000011111
 11111110000000000000000000000000000000001111111111111100000001111
 11111110000010000000000000000001100000000111011111111110000001111
 11111111000111110000000000000111110000000000111111111110110000111
 11111110001111111100010000000001111100000111111111111111110000111
 11111110001111111111111110000000111111100000000111111111111000111
 11111111001111111111111111111000000111111111111111111111111100011
 11111111101111111111111111111110000111111111111111111111111001111
 11111111111111111111111111111110001111111111111111111111100111111
 11111111111111111111111111111111001111111111111111111111001111111
 11111111111111111111111111111111100111111111111111111111111111111
 11111111111111111111111111111111110111111111111111111111111111111
 
 
 */
